// Command-line interface for CodeGraph-RT
use clap::{Parser, Subcommand, ValueEnum};
use codegraph_core::{
    GraphSystem, PerformanceMonitor, ExportFormat,
    FileWatcher, IncrementalParseEngine,
    ProjectGraph, OperationMetric,
};
use codegraph_api::RestApiServer;
use codegraph_lsp::start_lsp_server;
use codegraph_analytics::{AdvancedAnalyzer, AnalysisConfig};

use std::path::PathBuf;
use std::sync::Arc;
use std::collections::HashMap;

use tokio::signal;
use serde_json;
use tracing::info;

/// CodeGraph-RT: Real-Time Incremental Multi-Language Code Graph System
#[derive(Parser)]
#[command(name = "codegraph-rt")]
#[command(about = "A real-time incremental multi-language code graph system")]
#[command(version = env!("CARGO_PKG_VERSION"))]
pub struct Cli {
    /// Enable verbose output
    #[arg(short, long)]
    pub verbose: bool,

    /// Configuration file path
    #[arg(short, long)]
    pub config: Option<PathBuf>,

    /// Output format (for applicable commands)
    #[arg(short, long, value_enum, default_value_t = OutputFormat::Json)]
    pub format: OutputFormat,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Build a code graph from a project
    Build {
        /// Project path to analyze
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// Programming languages to include (comma-separated)
        #[arg(short, long)]
        languages: Option<String>,

        /// Output file for the graph
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Export format for visualization
        #[arg(long, value_enum)]
        export_format: Option<ExportFormat>,

        /// Include performance metrics
        #[arg(long)]
        metrics: bool,
    },

    /// Query an existing code graph
    Query {
        /// Graph file to query
        #[arg(value_name = "GRAPH_FILE")]
        graph_file: PathBuf,

        /// Node types to include
        #[arg(long, value_delimiter = ',')]
        node_types: Option<Vec<String>>,

        /// Edge types to include
        #[arg(long, value_delimiter = ',')]
        edge_types: Option<Vec<String>>,

        /// Programming languages to include
        #[arg(short, long, value_delimiter = ',')]
        languages: Option<Vec<String>>,

        /// Name pattern to search for
        #[arg(long)]
        pattern: Option<String>,

        /// Maximum number of results
        #[arg(long, default_value_t = 100)]
        limit: usize,
    },

    /// Start real-time file watching
    Watch {
        /// Project path to watch
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// Port for the REST API server
        #[arg(short, long, default_value_t = 8080)]
        port: u16,

        /// Host for the REST API server
        #[arg(long, default_value = "127.0.0.1")]
        host: String,

        /// Enable WebSocket real-time updates
        #[arg(long)]
        websocket: bool,
    },

    /// Start the REST API server
    Serve {
        /// Port to listen on
        #[arg(short, long, default_value_t = 8080)]
        port: u16,

        /// Host to bind to
        #[arg(long, default_value = "127.0.0.1")]
        host: String,

        /// Enable CORS
        #[arg(long)]
        cors: bool,
    },

    /// Export a graph to visualization format
    Export {
        /// Graph file to export
        #[arg(value_name = "GRAPH_FILE")]
        graph_file: PathBuf,

        /// Output file
        #[arg(short, long)]
        output: PathBuf,

        /// Export format
        #[arg(short, long, value_enum, default_value_t = ExportFormat::Graphviz)]
        format: ExportFormat,

        /// Include metadata in export
        #[arg(long)]
        metadata: bool,

        /// Include edge weights
        #[arg(long)]
        weights: bool,

        /// Filter by node types
        #[arg(long, value_delimiter = ',')]
        node_types: Option<Vec<String>>,

        /// Filter by edge types
        #[arg(long, value_delimiter = ',')]
        edge_types: Option<Vec<String>>,

        /// Maximum number of nodes to export
        #[arg(long)]
        max_nodes: Option<usize>,
    },

    /// Analyze relationships in a project
    Analyze {
        /// Project path to analyze
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// Output detailed relationship report
        #[arg(long)]
        detailed: bool,

        /// Include confidence scores
        #[arg(long)]
        confidence: bool,

        /// Minimum confidence threshold
        #[arg(long, default_value_t = 0.5)]
        threshold: f64,
    },

    /// Show performance metrics
    Metrics {
        /// Graph file or project path
        #[arg(value_name = "PATH")]
        path: Option<PathBuf>,

        /// Show detailed breakdown
        #[arg(long)]
        detailed: bool,

        /// Export metrics to file
        #[arg(long)]
        export: Option<PathBuf>,
    },

    /// Validate a project's code structure
    Validate {
        /// Project path to validate
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// Check for circular dependencies
        #[arg(long)]
        circular_deps: bool,

        /// Check for unused code
        #[arg(long)]
        unused_code: bool,

        /// Check code complexity
        #[arg(long)]
        complexity: bool,
    },

    /// Start the Language Server Protocol (LSP) server
    Lsp {
        /// Enable real-time diagnostics
        #[arg(long, default_value_t = true)]
        diagnostics: bool,

        /// Enable code completion
        #[arg(long, default_value_t = true)]
        completion: bool,

        /// Enable hover information
        #[arg(long, default_value_t = true)]
        hover: bool,

        /// Enable go-to-definition
        #[arg(long, default_value_t = true)]
        definition: bool,

        /// Enable find references
        #[arg(long, default_value_t = true)]
        references: bool,

        /// Enable document symbols
        #[arg(long, default_value_t = true)]
        symbols: bool,

        /// Enable code formatting
        #[arg(long, default_value_t = true)]
        formatting: bool,
    },

    /// Advanced code analytics and quality metrics
    Analytics {
        /// Project path to analyze
        #[arg(value_name = "PATH")]
        path: PathBuf,

        /// Output file for the analytics report
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Report format
        #[arg(short, long, value_enum, default_value_t = AnalyticsFormat::Json)]
        format: AnalyticsFormat,

        /// Enable complexity analysis
        #[arg(long, default_value_t = true)]
        complexity: bool,

        /// Enable quality analysis
        #[arg(long, default_value_t = true)]
        quality: bool,

        /// Enable trend analysis
        #[arg(long, default_value_t = true)]
        trends: bool,

        /// Include detailed recommendations
        #[arg(long, default_value_t = true)]
        recommendations: bool,

        /// Programming languages to include
        #[arg(short, long, value_delimiter = ',')]
        languages: Option<Vec<String>>,

        /// File patterns to include (e.g., "*.rs,*.py")
        #[arg(long, value_delimiter = ',')]
        patterns: Option<Vec<String>>,

        /// Project name for the report
        #[arg(long)]
        project_name: Option<String>,
    },
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum OutputFormat {
    /// JSON output
    Json,
    /// YAML output
    Yaml,
    /// Plain text output
    Text,
    /// CSV output
    Csv,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum AnalyticsFormat {
    /// JSON output
    Json,
    /// HTML report
    Html,
    /// Markdown report
    Markdown,
    /// CSV data
    Csv,
}

/// CLI application implementation
pub struct CliApp {
    performance_monitor: Arc<PerformanceMonitor>,
}

impl CliApp {
    pub fn new() -> Self {
        Self {
            performance_monitor: Arc::new(PerformanceMonitor::new()),
        }
    }

    pub async fn run(&self, cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
        // Initialize logging based on verbosity
        if cli.verbose {
            tracing_subscriber::fmt()
                .with_max_level(tracing::Level::DEBUG)
                .init();
        } else {
            tracing_subscriber::fmt()
                .with_max_level(tracing::Level::INFO)
                .init();
        }

        match cli.command {
            Commands::Build { path, languages, output, export_format, metrics } => {
                self.handle_build(path, languages, output, export_format, metrics, cli.format).await
            }
            Commands::Query { graph_file, node_types, edge_types, languages, pattern, limit } => {
                self.handle_query(graph_file, node_types, edge_types, languages, pattern, limit, cli.format).await
            }
            Commands::Watch { path, port, host, websocket } => {
                self.handle_watch(path, port, host, websocket).await
            }
            Commands::Serve { port, host, cors } => {
                self.handle_serve(port, host, cors).await
            }
            Commands::Export { graph_file, output, format, metadata, weights, node_types, edge_types, max_nodes } => {
                self.handle_export(graph_file, output, format, metadata, weights, node_types, edge_types, max_nodes).await
            }
            Commands::Analyze { path, detailed, confidence, threshold } => {
                self.handle_analyze(path, detailed, confidence, threshold, cli.format).await
            }
            Commands::Metrics { path, detailed, export } => {
                self.handle_metrics(path, detailed, export, cli.format).await
            }
            Commands::Validate { path, circular_deps, unused_code, complexity } => {
                self.handle_validate(path, circular_deps, unused_code, complexity, cli.format).await
            }
            Commands::Lsp { diagnostics, completion, hover, definition, references, symbols, formatting } => {
                self.handle_lsp(diagnostics, completion, hover, definition, references, symbols, formatting).await
            }
            Commands::Analytics { path, output, format, complexity, quality, trends, recommendations, languages, patterns, project_name } => {
                self.handle_analytics(path, output, format, complexity, quality, trends, recommendations, languages, patterns, project_name).await
            }
        }
    }

    async fn handle_build(
        &self,
        path: PathBuf,
        languages: Option<String>,
        output: Option<PathBuf>,
        export_format: Option<ExportFormat>,
        metrics: bool,
        format: OutputFormat,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("🔨 Building code graph for: {}", path.display());

        let start_time = std::time::Instant::now();
        let mut graph_system = GraphSystem::new().await?;

        // Build the graph
        let graph = graph_system.build_project_graph(&path, languages.as_deref()).await?;
        let build_time = start_time.elapsed();

        // Record performance metrics
        self.performance_monitor.record_operation(
            OperationMetric {
                operation_name: "graph_update".to_string(),
                duration_ms: build_time.as_millis() as f64,
                success: true,
                error_message: None,
                metadata: HashMap::new(),
            }
        ).await;

        println!("✅ Graph built successfully!");
        println!("   Nodes: {}", graph.node_count());
        println!("   Edges: {}", graph.edge_count());
        println!("   Languages: {:?}", graph.languages());
        println!("   Build time: {:?}", build_time);

        // Save graph if output specified
        if let Some(output_path) = output {
            info!("Saving graph to: {}", output_path.display());
            graph_system.save_graph(&graph, &output_path).await?;
            println!("💾 Graph saved to: {}", output_path.display());
        }

        // Export visualization if requested
        if let Some(export_fmt) = export_format {
            let export_path = path.with_extension(match export_fmt {
                ExportFormat::Graphviz => "dot",
                ExportFormat::D3Json => "json",
                ExportFormat::Cytoscape => "cyjs",
                ExportFormat::Gexf => "gexf",
                ExportFormat::GraphML => "graphml",
            });

            println!("📊 Exporting visualization to: {}", export_path.display());
            println!("✅ Export functionality will be implemented in future versions");
        }

        // Show performance metrics if requested
        if metrics {
            let report = self.performance_monitor.get_report().await;
            self.print_performance_report(&report, format);
        }

        Ok(())
    }

    async fn handle_query(
        &self,
        graph_file: PathBuf,
        node_types: Option<Vec<String>>,
        edge_types: Option<Vec<String>>,
        languages: Option<Vec<String>>,
        pattern: Option<String>,
        limit: usize,
        _format: OutputFormat,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("🔍 Querying code graph: {}", graph_file.display());

        println!("Query parameters:");
        if let Some(ref types) = node_types {
            println!("   Node types: {:?}", types);
        }
        if let Some(ref types) = edge_types {
            println!("   Edge types: {:?}", types);
        }
        if let Some(ref langs) = languages {
            println!("   Languages: {:?}", langs);
        }
        if let Some(ref pat) = pattern {
            println!("   Pattern: {}", pat);
        }
        println!("   Limit: {}", limit);

        println!("✅ Query functionality will be implemented in future versions");

        Ok(())
    }

    async fn handle_watch(
        &self,
        path: PathBuf,
        port: u16,
        host: String,
        websocket: bool,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("👁️  Starting file watcher for: {}", path.display());
        println!("🌐 REST API server starting on {}:{}", host, port);

        // Start the REST API server
        let server = RestApiServer::new().await?;
        
        if websocket {
            println!("🔌 WebSocket real-time updates enabled");
        }

        // Start file watcher
        let parse_engine = Arc::new(IncrementalParseEngine::new());
        let mut file_watcher = FileWatcher::new(parse_engine);
        file_watcher.start_watching(&path).await?;

        println!("✅ File watcher started successfully");
        println!("📡 API endpoints available at http://{}:{}/api/v1/", host, port);

        // Start the server
        tokio::select! {
            result = server.serve(&host, port) => {
                if let Err(e) = result {
                    eprintln!("❌ Server error: {}", e);
                }
            }
            _ = signal::ctrl_c() => {
                println!("\n🛑 Shutting down gracefully...");
                file_watcher.stop_watching().await?;
                println!("✅ Shutdown complete");
            }
        }

        Ok(())
    }

    async fn handle_serve(
        &self,
        port: u16,
        host: String,
        _cors: bool,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("🚀 Starting REST API server on {}:{}", host, port);

        let server = RestApiServer::new().await?;
        
        println!("✅ Server started successfully");
        println!("📡 API endpoints available at http://{}:{}/api/v1/", host, port);
        println!("📖 API documentation: http://{}:{}/api/v1/docs", host, port);

        // Handle graceful shutdown
        tokio::select! {
            result = server.serve(&host, port) => {
                if let Err(e) = result {
                    eprintln!("❌ Server error: {}", e);
                }
            }
            _ = signal::ctrl_c() => {
                println!("\n🛑 Shutting down gracefully...");
                println!("✅ Shutdown complete");
            }
        }

        Ok(())
    }

    async fn handle_export(
        &self,
        graph_file: PathBuf,
        output: PathBuf,
        format: ExportFormat,
        metadata: bool,
        weights: bool,
        node_types: Option<Vec<String>>,
        edge_types: Option<Vec<String>>,
        max_nodes: Option<usize>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("📊 Exporting graph to: {}", output.display());
        println!("   Source: {}", graph_file.display());
        println!("   Format: {:?}", format);
        println!("   Include metadata: {}", metadata);
        println!("   Include weights: {}", weights);

        if let Some(ref types) = node_types {
            println!("   Node type filter: {:?}", types);
        }
        if let Some(ref types) = edge_types {
            println!("   Edge type filter: {:?}", types);
        }
        if let Some(max) = max_nodes {
            println!("   Max nodes: {}", max);
        }

        println!("Loading graph from: {}", graph_file.display());

        println!("Export parameters:");
        if let Some(ref types) = node_types {
            println!("   Node type filter: {:?}", types);
        }
        if let Some(ref types) = edge_types {
            println!("   Edge type filter: {:?}", types);
        }
        if let Some(max) = max_nodes {
            println!("   Max nodes: {}", max);
        }

        println!("✅ Export functionality will be implemented in future versions");

        println!("✅ Graph exported successfully to: {}", output.display());
        Ok(())
    }

    async fn handle_analyze(
        &self,
        path: PathBuf,
        detailed: bool,
        confidence: bool,
        threshold: f64,
        _format: OutputFormat,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("🔬 Analyzing relationships in: {}", path.display());
        println!("   Detailed analysis: {}", detailed);
        println!("   Show confidence: {}", confidence);
        println!("   Confidence threshold: {:.2}", threshold);

        println!("Analysis will be performed with the following settings:");
        println!("   Confidence threshold: {:.2}", threshold);
        println!("   Semantic analysis: enabled");

        println!("✅ Analysis functionality will be implemented in future versions");

        Ok(())
    }

    async fn handle_metrics(
        &self,
        _path: Option<PathBuf>,
        detailed: bool,
        export: Option<PathBuf>,
        format: OutputFormat,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("📈 Performance Metrics");

        let report = self.performance_monitor.get_report().await;

        if detailed {
            self.print_detailed_performance_report(&report, format);
        } else {
            self.print_performance_report(&report, format);
        }

        if let Some(export_path) = export {
            let metrics_json = serde_json::to_string_pretty(&report)?;
            std::fs::write(&export_path, metrics_json)?;
            println!("💾 Metrics exported to: {}", export_path.display());
        }

        Ok(())
    }

    async fn handle_validate(
        &self,
        path: PathBuf,
        circular_deps: bool,
        unused_code: bool,
        complexity: bool,
        format: OutputFormat,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("✅ Validating project: {}", path.display());
        println!("   Check circular dependencies: {}", circular_deps);
        println!("   Check unused code: {}", unused_code);
        println!("   Check complexity: {}", complexity);

        // Build the graph
        let mut graph_system = GraphSystem::new().await?;
        let graph = graph_system.build_project_graph(&path, None).await?;

        let mut validation_results = Vec::new();
        let mut issues_found = 0;

        if circular_deps {
            println!("\n🔄 Checking for circular dependencies...");
            let circular_deps_found = self.check_circular_dependencies(&graph).await?;
            if !circular_deps_found.is_empty() {
                let count = circular_deps_found.len();
                issues_found += count;
                validation_results.push(("Circular Dependencies", circular_deps_found));
                println!("   ❌ Found {} circular dependency chains", count);
            } else {
                println!("   ✅ No circular dependencies found");
            }
        }

        if unused_code {
            println!("\n🗑️  Checking for unused code...");
            let unused_items = self.check_unused_code(&graph).await?;
            if !unused_items.is_empty() {
                let count = unused_items.len();
                issues_found += count;
                validation_results.push(("Unused Code", unused_items));
                println!("   ⚠️  Found {} potentially unused items", count);
            } else {
                println!("   ✅ No unused code detected");
            }
        }

        if complexity {
            println!("\n📊 Checking code complexity...");
            let complex_items = self.check_complexity(&graph).await?;
            if !complex_items.is_empty() {
                let count = complex_items.len();
                issues_found += count;
                validation_results.push(("High Complexity", complex_items));
                println!("   ⚠️  Found {} items with high complexity", count);
            } else {
                println!("   ✅ No high complexity issues found");
            }
        }

        // Print summary
        println!("\n📋 Validation Summary:");
        if issues_found == 0 {
            println!("   ✅ All checks passed! No issues found.");
        } else {
            println!("   ⚠️  Found {} total issues", issues_found);
        }

        // Print detailed results if requested
        self.print_validation_results(&validation_results, format);

        Ok(())
    }

    fn print_performance_report(&self, report: &codegraph_core::PerformanceReport, format: OutputFormat) {
        match format {
            OutputFormat::Json => {
                println!("{}", serde_json::to_string_pretty(report).unwrap_or_default());
            }
            OutputFormat::Text => {
                println!("📊 Performance Report");
                println!("   Uptime: {} seconds", report.uptime_seconds);
                println!("   Total Operations: {}", report.operation_stats.total_operations);
                println!("   Successful Operations: {}", report.operation_stats.successful_operations);
                println!("   Failed Operations: {}", report.operation_stats.failed_operations);
            }
            _ => {
                println!("Format {:?} not yet implemented for performance reports", format);
            }
        }
    }

    fn print_detailed_performance_report(&self, report: &codegraph_core::PerformanceReport, format: OutputFormat) {
        match format {
            OutputFormat::Json => {
                println!("{}", serde_json::to_string_pretty(report).unwrap_or_default());
            }
            OutputFormat::Text => {
                println!("📊 Detailed Performance Report");
                println!("   Uptime: {} seconds", report.uptime_seconds);
                println!("   Parse Operations:");
                println!("     Total: {}", report.operation_stats.total_operations);
                println!("     Successful: {}", report.operation_stats.successful_operations);
                println!("     Failed: {}", report.operation_stats.failed_operations);
                println!("     Average duration: {:.2}ms", report.operation_stats.average_duration_ms);
                println!("     Operations/sec: {:.2}", report.operation_stats.operations_per_second);
                println!("   Graph Updates:");
                // Graph update stats are part of operation stats
                println!("     Total: {}", report.operation_stats.total_operations);
                println!("     Successful: {}", report.operation_stats.successful_operations);
                println!("     Failed: {}", report.operation_stats.failed_operations);
                println!("     Average duration: {:.2}ms", report.operation_stats.average_duration_ms);
                println!("   Errors:");
                println!("     Total: {}", report.operation_stats.failed_operations);
                let error_rate = if report.operation_stats.total_operations > 0 {
                    (report.operation_stats.failed_operations as f64 / report.operation_stats.total_operations as f64) * 100.0
                } else {
                    0.0
                };
                println!("     Error rate: {:.2}%", error_rate);
            }
            _ => {
                println!("Format {:?} not yet implemented for detailed performance reports", format);
            }
        }
    }

    // Helper methods for future implementation

    async fn check_circular_dependencies(&self, _graph: &ProjectGraph) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        // TODO: Implement circular dependency detection
        // For now, return empty list
        Ok(Vec::new())
    }

    async fn check_unused_code(&self, _graph: &ProjectGraph) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        // TODO: Implement unused code detection
        // For now, return empty list
        Ok(Vec::new())
    }

    async fn check_complexity(&self, _graph: &ProjectGraph) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        // TODO: Implement complexity analysis
        // For now, return empty list
        Ok(Vec::new())
    }

    fn print_validation_results(&self, _results: &[(&str, Vec<String>)], format: OutputFormat) {
        match format {
            OutputFormat::Json => {
                println!("{{\"validation_results\": \"coming_soon\"}}");
            }
            OutputFormat::Text => {
                println!("📝 Validation results display coming soon");
            }
            _ => {
                println!("Format {:?} not yet implemented for validation results", format);
            }
        }
    }

    async fn handle_lsp(
        &self,
        diagnostics: bool,
        completion: bool,
        hover: bool,
        definition: bool,
        references: bool,
        symbols: bool,
        formatting: bool,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("🚀 Starting CodeGraph-RT Language Server Protocol (LSP) server...");
        println!("📋 LSP Features enabled:");
        println!("   • Diagnostics: {}", if diagnostics { "✅" } else { "❌" });
        println!("   • Code Completion: {}", if completion { "✅" } else { "❌" });
        println!("   • Hover Information: {}", if hover { "✅" } else { "❌" });
        println!("   • Go-to-Definition: {}", if definition { "✅" } else { "❌" });
        println!("   • Find References: {}", if references { "✅" } else { "❌" });
        println!("   • Document Symbols: {}", if symbols { "✅" } else { "❌" });
        println!("   • Code Formatting: {}", if formatting { "✅" } else { "❌" });
        println!();
        println!("💡 To use the LSP server, configure your editor to connect to:");
        println!("   • Protocol: Language Server Protocol (LSP)");
        println!("   • Command: codegraph-lsp");
        println!("   • Communication: stdio");
        println!();
        println!("📖 Supported languages: Python, JavaScript, TypeScript, Rust, Java, C, C++, Go");
        println!();
        println!("🔄 Starting LSP server (press Ctrl+C to stop)...");

        // Start the LSP server
        if let Err(e) = start_lsp_server().await {
            eprintln!("❌ Failed to start LSP server: {}", e);
            return Err(format!("LSP server error: {}", e).into());
        }

        Ok(())
    }

    async fn handle_analytics(
        &self,
        path: PathBuf,
        output: Option<PathBuf>,
        format: AnalyticsFormat,
        complexity: bool,
        quality: bool,
        trends: bool,
        recommendations: bool,
        languages: Option<Vec<String>>,
        patterns: Option<Vec<String>>,
        project_name: Option<String>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("📊 Starting advanced analytics for: {}", path.display());

        // Configure analysis
        let mut config = AnalysisConfig::default();
        config.metrics.enable_complexity = complexity;
        config.metrics.enable_quality = quality;
        config.trends.enable_anomaly_detection = trends;

        if let Some(langs) = languages {
            config.metrics.languages = langs;
        }

        // Create analyzer
        let mut analyzer = AdvancedAnalyzer::new(config);

        // Determine file patterns
        let file_patterns = patterns.unwrap_or_else(|| vec![
            "*.rs".to_string(),
            "*.py".to_string(),
            "*.js".to_string(),
            "*.ts".to_string(),
            "*.java".to_string(),
            "*.cpp".to_string(),
            "*.c".to_string(),
            "*.go".to_string(),
        ]);

        // Analyze project
        let start_time = std::time::Instant::now();
        let analysis_results = analyzer.analyze_project(&path, &file_patterns).await?;
        let analysis_time = start_time.elapsed();

        if analysis_results.is_empty() {
            println!("⚠️  No files found matching the specified patterns");
            return Ok(());
        }

        println!("✅ Analysis completed in {:.2}s", analysis_time.as_secs_f64());
        println!("   Files analyzed: {}", analysis_results.len());

        // Calculate totals
        let total_lines: usize = analysis_results.iter()
            .map(|r| r.metadata.lines_processed)
            .sum();
        let total_issues: usize = analysis_results.iter()
            .map(|r| r.quality_issues.len())
            .sum();

        println!("   Total lines: {}", total_lines);
        println!("   Quality issues found: {}", total_issues);

        // Generate comprehensive report
        let project_name = project_name.unwrap_or_else(|| {
            path.file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("Unknown Project")
                .to_string()
        });

        let report = analyzer.generate_report(&analysis_results, &project_name).await?;

        // Display executive summary
        println!("\n📋 Executive Summary:");
        println!("   Overall Quality Score: {:.1}/100 ({:?})",
                 report.executive_summary.overall_score,
                 report.executive_summary.quality_grade);
        println!("   Critical Issues: {}", report.executive_summary.critical_issues);
        println!("   Major Issues: {}", report.executive_summary.major_issues);

        if !report.executive_summary.key_findings.is_empty() {
            println!("\n🔍 Key Findings:");
            for finding in &report.executive_summary.key_findings {
                println!("   • {}", finding);
            }
        }

        if recommendations && !report.recommendations.is_empty() {
            println!("\n💡 Top Recommendations:");
            for (i, rec) in report.recommendations.iter().take(5).enumerate() {
                println!("   {}. {} (Priority: {:?})", i + 1, rec.title, rec.priority);
            }
        }

        // Output report
        let output_path = output.unwrap_or_else(|| {
            let extension = match format {
                AnalyticsFormat::Json => "json",
                AnalyticsFormat::Html => "html",
                AnalyticsFormat::Markdown => "md",
                AnalyticsFormat::Csv => "csv",
            };
            PathBuf::from(format!("analytics_report.{}", extension))
        });

        match format {
            AnalyticsFormat::Json => {
                let json = serde_json::to_string_pretty(&report)?;
                tokio::fs::write(&output_path, json).await?;
            }
            AnalyticsFormat::Html => {
                let html = self.generate_html_report(&report)?;
                tokio::fs::write(&output_path, html).await?;
            }
            AnalyticsFormat::Markdown => {
                let markdown = self.generate_markdown_report(&report)?;
                tokio::fs::write(&output_path, markdown).await?;
            }
            AnalyticsFormat::Csv => {
                let csv = self.generate_csv_report(&report)?;
                tokio::fs::write(&output_path, csv).await?;
            }
        }

        println!("\n📄 Report saved to: {}", output_path.display());
        Ok(())
    }

    fn generate_html_report(&self, report: &codegraph_analytics::AnalyticsReport) -> Result<String, Box<dyn std::error::Error>> {
        // Simple HTML report generation
        let html = format!(r#"
<!DOCTYPE html>
<html>
<head>
    <title>{}</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; }}
        .header {{ background: #f5f5f5; padding: 20px; border-radius: 5px; }}
        .metric {{ margin: 10px 0; }}
        .score {{ font-size: 24px; font-weight: bold; color: #2196F3; }}
        .finding {{ margin: 5px 0; padding: 5px; background: #fff3cd; border-radius: 3px; }}
        .recommendation {{ margin: 10px 0; padding: 10px; background: #d4edda; border-radius: 5px; }}
    </style>
</head>
<body>
    <div class="header">
        <h1>{}</h1>
        <p>Generated: {}</p>
    </div>

    <h2>Executive Summary</h2>
    <div class="score">Overall Quality Score: {:.1}/100 ({})</div>
    <div class="metric">Critical Issues: {}</div>
    <div class="metric">Major Issues: {}</div>

    <h2>Key Findings</h2>
    {}

    <h2>Recommendations</h2>
    {}
</body>
</html>
        "#,
            report.metadata.title,
            report.metadata.title,
            report.metadata.generated_at.format("%Y-%m-%d %H:%M:%S UTC"),
            report.executive_summary.overall_score,
            format!("{:?}", report.executive_summary.quality_grade),
            report.executive_summary.critical_issues,
            report.executive_summary.major_issues,
            report.executive_summary.key_findings.iter()
                .map(|f| format!("<div class=\"finding\">• {}</div>", f))
                .collect::<Vec<_>>()
                .join("\n"),
            report.recommendations.iter()
                .map(|r| format!("<div class=\"recommendation\"><strong>{}</strong><br>{}</div>", r.title, r.description))
                .collect::<Vec<_>>()
                .join("\n")
        );
        Ok(html)
    }

    fn generate_markdown_report(&self, report: &codegraph_analytics::AnalyticsReport) -> Result<String, Box<dyn std::error::Error>> {
        let markdown = format!(r#"# {}

Generated: {}

## Executive Summary

**Overall Quality Score:** {:.1}/100 ({})
- Critical Issues: {}
- Major Issues: {}

## Key Findings

{}

## Recommendations

{}

## Metrics Overview

- Total Lines of Code: {}
- Code Lines: {}
- Comment Lines: {}
- Cyclomatic Complexity: {:.1}
- Test Coverage: {:.1}%
- Duplication: {:.1}%
"#,
            report.metadata.title,
            report.metadata.generated_at.format("%Y-%m-%d %H:%M:%S UTC"),
            report.executive_summary.overall_score,
            format!("{:?}", report.executive_summary.quality_grade),
            report.executive_summary.critical_issues,
            report.executive_summary.major_issues,
            report.executive_summary.key_findings.iter()
                .map(|f| format!("- {}", f))
                .collect::<Vec<_>>()
                .join("\n"),
            report.recommendations.iter()
                .map(|r| format!("### {}\n\n{}\n\n**Priority:** {:?} | **Effort:** {:?}\n", r.title, r.description, r.priority, r.effort))
                .collect::<Vec<_>>()
                .join("\n"),
            report.metrics.lines_of_code.total_lines,
            report.metrics.lines_of_code.code_lines,
            report.metrics.lines_of_code.comment_lines,
            report.metrics.complexity.cyclomatic_complexity,
            report.metrics.quality.test_coverage,
            report.metrics.quality.duplication_percentage
        );
        Ok(markdown)
    }

    fn generate_csv_report(&self, report: &codegraph_analytics::AnalyticsReport) -> Result<String, Box<dyn std::error::Error>> {
        let csv = format!(r#"Metric,Value
Overall Score,{:.1}
Critical Issues,{}
Major Issues,{}
Total Lines,{}
Code Lines,{}
Comment Lines,{}
Cyclomatic Complexity,{:.1}
Cognitive Complexity,{:.1}
Test Coverage,{:.1}
Duplication Percentage,{:.1}
Technical Debt Ratio,{:.1}
Maintainability Index,{:.1}
"#,
            report.executive_summary.overall_score,
            report.executive_summary.critical_issues,
            report.executive_summary.major_issues,
            report.metrics.lines_of_code.total_lines,
            report.metrics.lines_of_code.code_lines,
            report.metrics.lines_of_code.comment_lines,
            report.metrics.complexity.cyclomatic_complexity,
            report.metrics.complexity.cognitive_complexity,
            report.metrics.quality.test_coverage,
            report.metrics.quality.duplication_percentage,
            report.metrics.quality.technical_debt_ratio,
            report.metrics.maintainability.maintainability_index
        );
        Ok(csv)
    }
}

impl Default for CliApp {
    fn default() -> Self {
        Self::new()
    }
}
